package cocom.iplatform.piaoerbai.controller;

import cocom.iplatform.piaoerbai.bean.BasicDataBean;
import cocom.iplatform.piaoerbai.bean.ResultBean;
import cocom.iplatform.piaoerbai.constants.BaseConstants;
import cocom.iplatform.piaoerbai.service.impl.BasicDataServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/basicData")
public class BasicDataController {
    @Resource
    private BasicDataServiceImpl basicDataService;

    @PostMapping("/addBasicData")
    public ResultBean addBasicData(@RequestBody BasicDataBean basicDataBean){
        if (basicDataBean==null){
            return new ResultBean(400,"failed,data should not be null");
        }
        try {
            basicDataService.addBasicData(basicDataBean);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean(400,"insert data failed");
        }
         return new ResultBean(200,"success");
    }

    @GetMapping("/deleteById")
    public ResultBean deleteById(@RequestParam Integer id){
        try {
            basicDataService.deleteBasicDataById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean(400,"delete data failed");
        }
        return new ResultBean(200,"success");
    }

    @PostMapping("/updateBasicData")
    public ResultBean updateBasicData(@RequestBody BasicDataBean basicDataBean){
        if (basicDataBean==null){
            return new ResultBean(400,"failed,data should not be null");
        }
        try {
            basicDataService.updateBasicData(basicDataBean);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean(400,"update data failed");
        }
        return new ResultBean(200,"success");
    }

    @GetMapping("/getDataById")
    public ResultBean getDataById(@RequestParam  Integer id){
        BasicDataBean basicData = basicDataService.getBasicDataById(id);
        return new ResultBean(200,"success",basicData);
    }

    @GetMapping("/getAllData")
    public ResultBean getAllData(){
        List<BasicDataBean> allBasicData = basicDataService.getAllBasicData();
        return new ResultBean(200,"success",allBasicData);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultBean exceptionHandler(Exception e) {
        return new ResultBean(BaseConstants.FAILED, e.getMessage());
    }

}
